<!-- eslint-disable unused-imports/no-unused-vars -->
<script setup lang="ts">
import type { FormRules } from "element-plus"
import type { CreateOrUpdatePositionRequest, PositionInfo, PositionQuery } from "./apis/type"
import { usePagination } from "@@/composables/usePagination"
import { CirclePlus, RefreshRight, Search, Upload } from "@element-plus/icons-vue"
import { cloneDeep } from "lodash-es"
import {
  createPositionApi,
  getAvailableEnterpriseListApi,
  getPositionListApi,
  updatePositionApi,
  updatePositionStatusApi,
  uploadJobDescriptionApi
} from "./apis/position"

// 常量定义
const POSITION_TYPE_OPTIONS = [
  { label: "技术开发", value: "development" },
  { label: "产品管理", value: "product" },
  { label: "数据分析", value: "data" },
  { label: "市场运营", value: "marketing" },
  { label: "行政人事", value: "hr" },
  { label: "其他", value: "other" }
]

const WORK_TYPE_OPTIONS = [
  { label: "线下", value: "offline" },
  { label: "线上", value: "online" },
  { label: "混合模式", value: "hybrid" }
]

const SALARY_RANGE_OPTIONS = [
  { label: "100-150元/天", value: "100-150/day" },
  { label: "150-200元/天", value: "150-200/day" },
  { label: "200-300元/天", value: "200-300/day" },
  { label: "1500-2500元/月", value: "1500-2500/month" },
  { label: "2500-3500元/月", value: "2500-3500/month" },
  { label: "3500元/月以上", value: "3500+/month" }
]

const INTERNSHIP_PERIOD_OPTIONS = [
  { label: "2个月", value: "2m" },
  { label: "3个月", value: "3m" },
  { label: "6个月", value: "6m" },
  { label: "灵活安排", value: "flexible" }
]

const MAJOR_OPTIONS = [
  { label: "计算机科学与技术", value: "cs" },
  { label: "软件工程", value: "se" },
  { label: "数据科学与大数据技术", value: "data-science" },
  { label: "电子信息工程", value: "ee" },
  { label: "通信工程", value: "comm" },
  { label: "不限专业", value: "any" }
]

// 响应式数据
const loading = ref<boolean>(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
const positionList = ref<PositionInfo[]>([])
const enterpriseOptions = ref<Array<{ id: number, name: string }>>([])

// 搜索表单
const searchFormRef = useTemplateRef("searchFormRef")
const searchData = reactive<Partial<Pick<PositionQuery, "positionName" | "enterpriseName" | "status">>>({
  positionName: "",
  enterpriseName: "",
  status: ""
})

// 编辑表单
const dialogVisible = ref<boolean>(false)
const previewVisible = ref<boolean>(false)
const formRef = useTemplateRef("formRef")
const DEFAULT_FORM_DATA: CreateOrUpdatePositionRequest = {
  id: undefined,
  enterpriseId: 0,
  positionName: "",
  positionType: "development",
  workType: "offline",
  workCity: "",
  salaryRange: "100-150/day",
  internshipPeriod: "3m",
  startDate: "",
  recruitmentCount: 1,
  majorRequirements: [],
  skillRequirements: "",
  jobResponsibilities: "",
  applicationDeadline: "",
  contactInfo: "",
  status: "recruiting"
}
const formData = ref<CreateOrUpdatePositionRequest>(cloneDeep(DEFAULT_FORM_DATA))

// 表单验证规则
const formRules: FormRules<CreateOrUpdatePositionRequest> = {
  enterpriseId: [{ required: true, trigger: "change", message: "请选择企业" }],
  positionName: [{ required: true, trigger: "blur", message: "请输入岗位名称" }],
  positionType: [{ required: true, trigger: "change", message: "请选择岗位类型" }],
  workType: [{ required: true, trigger: "change", message: "请选择工作类型" }],
  workCity: [
    {
      required: true,
      trigger: "blur",
      message: "请输入工作城市",
      validator: (rule, value, callback) => {
        if (formData.value.workType === "online" || value) {
          callback()
        } else {
          callback(new Error("请输入工作城市"))
        }
      }
    }
  ],
  salaryRange: [{ required: true, trigger: "change", message: "请选择薪资范围" }],
  internshipPeriod: [{ required: true, trigger: "change", message: "请选择实习周期" }],
  startDate: [
    { required: true, trigger: "change", message: "请选择任职开始时间" },
    {
      validator: (rule, value, callback) => {
        if (!value) return callback()
        const today = new Date()
        today.setHours(0, 0, 0, 0)
        const selectedDate = new Date(value)
        if (selectedDate < today) {
          callback(new Error("任职开始时间不能早于今天"))
        } else {
          callback()
        }
      },
      trigger: "change"
    }
  ],
  recruitmentCount: [
    { required: true, trigger: "blur", message: "请输入招聘人数" },
    { type: "number", min: 1, trigger: "blur", message: "招聘人数至少为1人" }
  ],
  skillRequirements: [{ required: true, trigger: "blur", message: "请输入技能要求" }],
  jobResponsibilities: [{ required: true, trigger: "blur", message: "请输入岗位职责" }],
  applicationDeadline: [
    { required: true, trigger: "change", message: "请选择报名截止日期" },
    {
      validator: (rule, value, callback) => {
        if (!value || !formData.value.startDate) return callback()
        const deadline = new Date(value)
        const startDate = new Date(formData.value.startDate)
        if (deadline >= startDate) {
          callback(new Error("报名截止日期必须早于任职开始时间"))
        } else {
          callback()
        }
      },
      trigger: "change"
    }
  ],
  contactInfo: [{ required: true, trigger: "blur", message: "请输入联系方式" }]
}

// 方法定义
async function getEnterpriseList() {
  try {
    const { data } = await getAvailableEnterpriseListApi()
    enterpriseOptions.value = data
  } catch (_error) {
    ElMessage.error("获取企业列表失败")
  }
}

async function getPositionList() {
  loading.value = true
  try {
    const { data } = await getPositionListApi({
      currentPage: paginationData.currentPage,
      size: paginationData.pageSize,
      ...searchData
    })
    paginationData.total = data.total
    positionList.value = data.list
  } catch (error) {
    ElMessage.error("获取岗位列表失败")
    positionList.value = []
  } finally {
    loading.value = false
  }
}

function handleSearch() {
  paginationData.currentPage = 1
  getPositionList()
}

function resetSearch() {
  searchFormRef.value?.resetFields()
  handleSearch()
}

function openAddDialog() {
  resetForm()
  dialogVisible.value = true
}

function openEditDialog(position: PositionInfo) {
  formData.value = cloneDeep(position)
  dialogVisible.value = true
}

function resetForm() {
  formRef.value?.clearValidate()
  formData.value = cloneDeep(DEFAULT_FORM_DATA)
}

async function handleSave() {
  await formRef.value?.validate()
  loading.value = true
  try {
    const api = formData.value.id ? updatePositionApi : createPositionApi
    await api(formData.value)
    ElMessage.success(formData.value.id ? "更新成功" : "发布成功")
    dialogVisible.value = false
    getPositionList()
  } catch (error) {
    ElMessage.error(formData.value.id ? "更新失败" : "发布失败")
  } finally {
    loading.value = false
  }
}

async function handleClosePosition(id: number) {
  try {
    await updatePositionStatusApi(id, "closed")
    ElMessage.success("已下架该岗位")
    getPositionList()
  } catch (error) {
    ElMessage.error("操作失败，请稍后重试")
  }
}

async function handleUploadJobDescription(file: File) {
  // 检查文件类型
  const validTypes = ["application/pdf", "application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"]
  if (!validTypes.includes(file.type)) {
    ElMessage.error("只支持PDF、Word格式的文件")
    return false
  }

  try {
    const { data } = await uploadJobDescriptionApi(file)
    formData.value.jobDescriptionUrl = data.url
    ElMessage.success("上传成功")
    return true
  } catch (error) {
    ElMessage.error("上传失败，请稍后重试")
    return false
  }
}

function handlePreview() {
  previewVisible.value = true
}

// 监听工作类型变化，自动设置远程城市
watch(() => formData.value.workType, (newWorkType) => {
  if (newWorkType === "online") {
    formData.value.workCity = "远程"
  } else if (formData.value.workCity === "远程") {
    formData.value.workCity = ""
  }
})

// 监听分页变化
watch([() => paginationData.currentPage, () => paginationData.pageSize], getPositionList)

// 初始化数据
onMounted(async () => {
  await getEnterpriseList()
  getPositionList()
})
</script>

<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="positionName" label="岗位名称">
          <el-input v-model="searchData.positionName" placeholder="请输入岗位名称" />
        </el-form-item>
        <el-form-item prop="enterpriseName" label="企业名称">
          <el-input v-model="searchData.enterpriseName" placeholder="请输入企业名称" />
        </el-form-item>
        <el-form-item prop="status" label="岗位状态">
          <el-select v-model="searchData.status" placeholder="请选择" clearable style="width: 120px;">
            <el-option label="招聘中" value="recruiting" />
            <el-option label="已截止" value="closed" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">
            查询
          </el-button>
          <el-button :icon="RefreshRight" @click="resetSearch">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作和表格区域 -->
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <el-button type="primary" :icon="CirclePlus" @click="openAddDialog">
          发布岗位
        </el-button>
      </div>

      <el-table :data="positionList" style="width: 100%">
        <el-table-column prop="positionName" label="岗位名称" width="180" />
        <el-table-column prop="enterpriseName" label="企业名称" width="180" />
        <el-table-column prop="positionType" label="岗位类型" width="120">
          <template #default="scope">
            <el-tag>
              {{ POSITION_TYPE_OPTIONS.find(item => item.value === scope.row.positionType)?.label || scope.row.positionType }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="workType" label="工作类型" width="100">
          <template #default="scope">
            <el-tag>
              {{ WORK_TYPE_OPTIONS.find(item => item.value === scope.row.workType)?.label || scope.row.workType }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="workCity" label="工作城市" width="100" />
        <el-table-column prop="salaryRange" label="薪资范围" width="120">
          <template #default="scope">
            <el-tag type="primary">
              {{ SALARY_RANGE_OPTIONS.find(item => item.value === scope.row.salaryRange)?.label || scope.row.salaryRange }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="recruitmentCount" label="招聘人数" width="80" />
        <el-table-column prop="applicationDeadline" label="截止日期" width="150" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 'recruiting'" type="success">
              招聘中
            </el-tag>
            <el-tag v-else type="danger">
              已截止
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="180" align="center">
          <template #default="scope">
            <el-button type="primary" text @click="openEditDialog(scope.row)">
              编辑
            </el-button>
            <el-button
              v-if="scope.row.status === 'recruiting'"
              type="danger"
              text
              @click="handleClosePosition(scope.row.id!)"
            >
              下架
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :current-page="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="formData.id ? '编辑岗位' : '发布岗位'"
      width="70%"
      @closed="resetForm"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px">
        <!-- 企业信息 -->
        <el-form-item prop="enterpriseId" label="选择企业">
          <el-select v-model="formData.enterpriseId" placeholder="请选择企业">
            <el-option
              v-for="item in enterpriseOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <!-- 岗位基本信息 -->
        <el-form-item prop="positionName" label="岗位名称">
          <el-input v-model="formData.positionName" placeholder="请输入岗位名称" />
        </el-form-item>
        <el-form-item prop="positionType" label="岗位类型">
          <el-select v-model="formData.positionType" placeholder="请选择">
            <el-option
              v-for="item in POSITION_TYPE_OPTIONS"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="workType" label="工作类型">
          <el-radio-group v-model="formData.workType">
            <el-radio v-for="item in WORK_TYPE_OPTIONS" :key="item.value" :label="item.value">
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="workCity" label="工作城市" v-if="formData.workType !== 'online'">
          <el-input v-model="formData.workCity" placeholder="请输入工作城市" />
        </el-form-item>
        <el-form-item prop="salaryRange" label="薪资范围">
          <el-select v-model="formData.salaryRange" placeholder="请选择">
            <el-option
              v-for="item in SALARY_RANGE_OPTIONS"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="internshipPeriod" label="实习周期">
          <el-select v-model="formData.internshipPeriod" placeholder="请选择">
            <el-option
              v-for="item in INTERNSHIP_PERIOD_OPTIONS"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="startDate" label="任职开始时间">
          <el-date-picker
            v-model="formData.startDate"
            type="date"
            placeholder="选择日期"
            style="width: 100%"
            :disabled-date="(time: Date) => time.getTime() < Date.now() - 8.64e7"
          />
        </el-form-item>
        <el-form-item prop="recruitmentCount" label="招聘人数">
          <el-input-number
            v-model="formData.recruitmentCount"
            :min="1"
            style="width: 100%"
          />
        </el-form-item>

        <!-- 岗位要求与职责 -->
        <el-form-item prop="majorRequirements" label="专业限制">
          <el-checkbox-group v-model="formData.majorRequirements">
            <el-checkbox
              v-for="item in MAJOR_OPTIONS"
              :key="item.value"
              :label="item.value"
            >
              {{ item.label }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item prop="skillRequirements" label="技能要求">
          <el-input v-model="formData.skillRequirements" placeholder="请输入技能要求" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item prop="jobResponsibilities" label="岗位职责">
          <el-input v-model="formData.jobResponsibilities" placeholder="请输入岗位职责" type="textarea" :rows="3" />
        </el-form-item>

        <!-- 附件上传 -->
        <el-form-item label="岗位说明书">
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :on-success="() => {}"
            :before-upload="handleUploadJobDescription"
            action=""
            :auto-upload="false"
          >
            <img v-if="formData.jobDescriptionUrl" :src="formData.jobDescriptionUrl" class="avatar">
            <el-icon v-else class="avatar-uploader-icon">
              <Upload />
            </el-icon>
          </el-upload>
          <div class="upload-tip">
            支持PDF、Word格式文件
          </div>
        </el-form-item>

        <!-- 报名规则 -->
        <el-form-item prop="applicationDeadline" label="报名截止日期">
          <el-date-picker
            v-model="formData.applicationDeadline"
            type="date"
            placeholder="选择日期"
            style="width: 100%"
            :disabled-date="(time: Date) => {
              if (!formData.startDate) return false
              return time.getTime() >= new Date(formData.startDate).getTime()
            }"
          />
        </el-form-item>
        <el-form-item prop="contactInfo" label="联系方式">
          <el-input v-model="formData.contactInfo" placeholder="请输入联系方式" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handlePreview">
          预览
        </el-button>
        <el-button @click="dialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" :loading="loading" @click="handleSave">
          {{ formData.id ? '更新' : '发布' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 预览对话框 -->
    <el-dialog
      v-model="previewVisible"
      title="岗位详情预览"
      width="80%"
    >
      <div class="preview-content">
        <h3>{{ formData.positionName }}</h3>
        <div class="preview-item">
          <span class="preview-label">企业名称：</span>
          <span>{{ enterpriseOptions.find(e => e.id === formData.enterpriseId)?.name }}</span>
        </div>
        <div class="preview-item">
          <span class="preview-label">岗位类型：</span>
          <span>{{ POSITION_TYPE_OPTIONS.find(item => item.value === formData.positionType)?.label }}</span>
        </div>
        <div class="preview-item">
          <span class="preview-label">工作类型：</span>
          <span>{{ WORK_TYPE_OPTIONS.find(item => item.value === formData.workType)?.label }}</span>
        </div>
        <div class="preview-item">
          <span class="preview-label">工作城市：</span>
          <span>{{ formData.workCity }}</span>
        </div>
        <div class="preview-item">
          <span class="preview-label">薪资范围：</span>
          <span>{{ SALARY_RANGE_OPTIONS.find(item => item.value === formData.salaryRange)?.label }}</span>
        </div>
        <div class="preview-item">
          <span class="preview-label">实习周期：</span>
          <span>{{ INTERNSHIP_PERIOD_OPTIONS.find(item => item.value === formData.internshipPeriod)?.label }}</span>
        </div>
        <div class="preview-item">
          <span class="preview-label">任职开始时间：</span>
          <span>{{ formData.startDate }}</span>
        </div>
        <div class="preview-item">
          <span class="preview-label">招聘人数：</span>
          <span>{{ formData.recruitmentCount }}人</span>
        </div>
        <div class="preview-item">
          <span class="preview-label">专业限制：</span>
          <span>
            <span v-for="major in formData.majorRequirements" :key="major" class="major-tag">
              {{ MAJOR_OPTIONS.find(item => item.value === major)?.label }}
            </span>
            <span v-if="formData.majorRequirements.length === 0">无</span>
          </span>
        </div>
        <div class="preview-section">
          <h4>技能要求</h4>
          <p>{{ formData.skillRequirements }}</p>
        </div>
        <div class="preview-section">
          <h4>岗位职责</h4>
          <p>{{ formData.jobResponsibilities }}</p>
        </div>
        <div class="preview-item">
          <span class="preview-label">报名截止日期：</span>
          <span>{{ formData.applicationDeadline }}</span>
        </div>
        <div class="preview-item">
          <span class="preview-label">联系方式：</span>
          <span>{{ formData.contactInfo }}</span>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.search-wrapper {
  margin-bottom: 20px;
}

.toolbar-wrapper {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-start;
}

.pager-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
  border: 1px dashed #dcdfe6;
  border-radius: 6px;
  cursor: pointer;
  background-color: #f0f2f5;
  overflow: hidden;
}

.upload-tip {
  margin-top: 8px;
  color: #909399;
  font-size: 12px;
}

/* 预览样式 */
.preview-content {
  line-height: 1.8;
}

.preview-content h3 {
  text-align: center;
  margin-bottom: 20px;
  color: #303133;
}

.preview-content h4 {
  margin: 16px 0 8px 0;
  color: #606266;
}

.preview-item {
  margin-bottom: 12px;
}

.preview-label {
  display: inline-block;
  width: 120px;
  color: #606266;
  font-weight: 500;
}

.major-tag {
  display: inline-block;
  padding: 2px 8px;
  background-color: #ecf5ff;
  color: #409eff;
  border-radius: 4px;
  margin-right: 8px;
  margin-bottom: 8px;
}

.preview-section {
  margin: 20px 0;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 4px;
}
</style>
